package model;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class RepositorioModelo {

	EntityManagerFactory emf;
	EntityManager em;
	
	public RepositorioModelo(){
		emf = Persistence.createEntityManagerFactory("dbteste");
		em = emf.createEntityManager();
	}
	
	public void salvar(Modelo modelo){
		
		em.getTransaction().begin();
		em.merge(modelo); //se o Objeto já existir no BD o Hibernate tentará atualizá-lo
		em.getTransaction().commit();
		emf.close();
		
	}
	
	public Modelo buscarPorId (int id){
		
		em.getTransaction().begin();
		Modelo modelo = em.find(Modelo.class, id);
		em.getTransaction().commit();
		emf.close();
		return modelo;
		
	}
	
	public void remover (Modelo modelo){
		
		em.getTransaction().begin();
		em.remove(modelo); 
		em.getTransaction().commit();
		emf.close();
	}
	
	@SuppressWarnings("unchecked")
	public List<Modelo> listarTodos(){
		
		em.getTransaction().begin();
		Query consulta = em.createNamedQuery("SELECT a FROM Automovel a");
		List<Modelo>  modelo = consulta.getResultList();
		em.getTransaction().commit();
		emf.close();
		return modelo;
	}
}
